import { defineStore } from "pinia";
import { IconVO } from "@/entiy/vo/IconVO.ts";
import PromiseUtils from "@/utils/PromiseUtils.ts";
import { VxeMenuPropTypes } from "vxe-pc-ui";
import { MenuUtils } from "@/utils/MenuUtils.ts";
import { routeConfigs } from "@/router/config.ts";
import { SocketUtils } from "@/utils/SocketUtils.ts";
import RequestService from "@/service/RequestService.ts";
import { SystemRoleMenuInfoVO } from "@/entiy/vo/SystemRoleMenuInfoVO.ts";

export const useGlobalStore = defineStore("useGlobalStore", {
    state: () => {
        return {
            menuList: [] as VxeMenuPropTypes.Options,
            iconList: [] as Array<IconVO>,
        }
    },

    actions: {
        // 加载全局数据
        async loadGlobalData(): Promise<void> {
            try {
                await Promise.all([
                    // 加载菜单数据
                    this.loadMenuData(),
                    // 加载图标数据
                    this.loadIconData(),
                    // 连接 Socket
                    this.connectSocket(),
                ])
            } catch (e) {
                return PromiseUtils.rejectSystemError();
            }
        },

        // 加载全局的菜单数据
        async loadMenuData() {
            const result = await RequestService.get<Array<SystemRoleMenuInfoVO>>("/query-system-role-menu-info-list");
            if (result.isError) {
                return PromiseUtils.reject(result.errorMsg);
            }

            const roleMenuInfoList: Array<SystemRoleMenuInfoVO> = result.bizDta;
            this.menuList = MenuUtils.convertRouteToVxeMenu(routeConfigs, roleMenuInfoList);
            return PromiseUtils.resolve();
        },

        // 加载全局的图标数据
        async loadIconData() {
            const result = await RequestService.get<Array<IconVO>>("/anonymous/get-all-icon-list");
            if (result.isError) {
                return PromiseUtils.reject(result.errorMsg);
            }

            this.iconList = result.bizDta;
            return PromiseUtils.resolve();
        },

        // 连接 Socket
        async connectSocket() {
            // 初始化 Socket（只需初始化一次）
            SocketUtils.initSocket();
            SocketUtils.socket.on("SYSTEM_NOTICE", (...args) => {
                console.log("收到系统消息:", args[0])
            });
        }
    }
})
